
#import "JfPay.h"
#import "NSData+AES.h"
#import "NSData+JFTBase64.h"
#import "JFTWebViewControler.h"
#import "JFTPayModel.h"
#import "JFTConfigureHeader.h"
#import "WXApi.h"
#import "JFTDES.h"
#import "JFTRequest.h"
#import "JHShare.h"
#import "JFTCheckViewController.h"
typedef NS_ENUM(NSUInteger, junFuTongPayType){
    JFTNonePayType    = 0,
    JFTWeiXinPayType  = 1,
    JFTAlipayPayType  = 2,
    JFTJDpayPayType   = 3,
    JFTQQpayPayType   = 4,
};
typedef enum ParamaterTypes ParamaterType;
const NSArray *___ParamaterType;
NSString *order_Id = nil;
NSString *key_String = nil;
NSString *iv_String  = nil;
UIViewController *model_VC = nil;

@implementation JfPay
static BOOL KDS_Log_Switch = NO;

id <JftSDKPayDelegate> jftMydelegate = nil;
#pragma mark - getPaytypeListEntrance
+ (void)getPayTypeListWithApplicationNumber:(NSString *)applicationNumber aesKey:(NSString *)key andAesIv:(NSString *)iv returnDelegate:(id<JftSDKPayDelegate>)delegate{
    //    isOneStep =NO;
    if (!applicationNumber||!key||!iv) {
        [delegate getPayTypeListFailure:@"参数缺失"];
        JFT_Log(@"参数缺失");
        return;
    }
    if (![self getServiceUrl:MIWENKEY]) {
        [self getConfigureURLwithApplicationNumber:applicationNumber aesKey:key andAesIv:iv serviceType:nil andDelegate:delegate payListArray:^(NSString *url) {
            [self getPayTypeListWithApplication_Number:applicationNumber aes_Key:key andAes_Iv:iv return_Delegate:delegate];
        }];
    }else{
        
        NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
        NSString * miWen = [self getServiceUrl:MIWENKEY];
        NSData * de_data = [[NSData dataFromBase64String:miWen] AES256DecryptWithKey:key iv:iv];
        NSError * mingError;
        NSDictionary * mingwenDic=[NSJSONSerialization JSONObjectWithData:de_data options:NSJSONReadingAllowFragments error:&mingError];
        NSString * nextSync =[mingwenDic objectForKey:@"nextSync"];
        NSTimeInterval nextInterval =[nextSync doubleValue]/1000;
        
        if (interval>nextInterval) {
            [self getConfigureURLwithApplicationNumber:applicationNumber aesKey:key andAesIv:iv serviceType:nil andDelegate:delegate payListArray:^(NSString *url) {
                [self getPayTypeListWithApplicationNumber:applicationNumber aesKey:key andAesIv:iv returnDelegate:delegate];
            }];
        }else{
            [self getPayTypeListWithApplication_Number:applicationNumber aes_Key:key andAes_Iv:iv return_Delegate:delegate];
        }
    }
    
}
# pragma mark - getServerlist
+ (void)getConfigureURLwithApplicationNumber:(NSString *)applicationNumber aesKey:(NSString *)key andAesIv:(NSString *)iv serviceType:(NSString*)type andDelegate:(id<JftSDKPayDelegate>)delegate payListArray:(void (^)(NSString*url))payList{
    NSString *serviceType = type ? type : @"CFT";
   
    NSDictionary *sysDic = @{@"CFT":@"https://api.paycheng.com",@"JFT":@"http://ywapi.jtpay.com",@"JFTCS":@"http://3ywapi.jtpay.com"};
    NSDictionary *orderDic = @{@"CFT":@"https://order.paycheng.com/jh-web-order/order/receiveOrder",@"JFT":@"http://order.jtpay.com/jh-web-order/order/receiveOrder",@"JFTCS":@"http://3order.jtpay.com/jh-web-order/order/receiveOrder"};
    NSString *defaultUrl =type ? [sysDic objectForKey:serviceType] : JFTBASEURL;
    
    NSDictionary *dic=@{@"sysFlag":serviceType};
    NSError  *error;
    NSData   *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    
    NSData   *en_data1 = [data AES256EncryptWithKey:key iv:iv];
    NSString *base64=[JFTDES replaceNormalCharacter:[en_data1 base64EncodedString]];
    NSString *encodeBase64 =[JFTDES encodeToPercentEscapeString:base64];
    
    NSString *parmaUrl =[NSString stringWithFormat:@"%@/services/getServerApiList/%@/%@",defaultUrl,applicationNumber,encodeBase64];
    NSURL *url=[NSURL URLWithString:parmaUrl];
    JFT_Log(@"/services/getServerApiList/%@/%@",applicationNumber,encodeBase64);
    //获取配置文件请求；
    //    __weak typeof(self)weakSelf =self;
    [[JFTRequest requestManager]getDataWithUrl:url WithParameters:@{} Sucessfil:^(id returnData) {
        JFT_Log(@"配置文件=%@",returnData);
        if ([returnData isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic =(NSDictionary*)returnData;
            if ([[dic objectForKey:@"flag"] integerValue]==1 ) {
                NSString *miWen =[JFTDES replaceSpecialcharacter:[dic objectForKey:@"msg"]];
                NSData *de_data = [[NSData dataFromBase64String:miWen] AES256DecryptWithKey:key iv:iv];
                if (!de_data) {
                    return ;
                }
                NSError *jsonError=nil;
                NSArray *services =nil;
                NSArray *orderServices =nil;
                NSDictionary *ddic =nil;
                if ([[NSJSONSerialization
                      JSONObjectWithData:de_data
                      options:NSJSONReadingMutableContainers
                      error:&jsonError] isKindOfClass:[NSDictionary class]]) {
                    ddic = [NSJSONSerialization
                            JSONObjectWithData:de_data
                            options:NSJSONReadingMutableContainers
                            error:&jsonError];
                    services       = [ddic objectForKey:@"apiServices"];
                    orderServices  = [ddic objectForKey:@"orderServices"];
                }
             
              
                JFT_Log(@"services=%d orderServices=%d",services.count,orderServices.count);
                if (services.count && orderServices.count) {
                    
                    [self storageServiceUrl:miWen WithKey:MIWENKEY];
                    
                    [self storageServiceUrl:[services objectAtIndex:0] WithKey:BASEJFTURLKEY];
                [self storageServiceUrl:[orderServices objectAtIndex:0] WithKey:PAYURLKEY];
                NSString *firstUrlString =[services objectAtIndex:0];
                    payList (firstUrlString);
                    
                }
                
            }else{
                
            if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
                    [delegate openAppFailer:dic[@"msg"]];
                }
                [self storageServiceUrl:[orderDic objectForKey:serviceType] WithKey:PAYURLKEY];
                     [self storageServiceUrl:[sysDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
                      payList (@"");
                 }
                }
        
        
    } failure:^(id failerObjc) {
        if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
            [delegate openAppFailer:failerObjc];
        }
        [self storageServiceUrl:[orderDic objectForKey:serviceType] WithKey:PAYURLKEY];
        [self storageServiceUrl:[sysDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
        payList (@"");

        
    }error:^(NSError *err) {
        if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
            [delegate openAppFailer:[NSString stringWithFormat:@"%ld",(long)err.code]];
        }
        [self storageServiceUrl:[orderDic objectForKey:serviceType] WithKey:PAYURLKEY];
        [self storageServiceUrl:[sysDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
        payList (@"");

    }];
}
#pragma mark - getPaytypeList
+ (void) getPayTypeListWithApplication_Number:(NSString*)application_Number aes_Key:(NSString*)key andAes_Iv:(NSString*)iv return_Delegate:(id<JftSDKPayDelegate>)delegate{
    NSString *payUrl = [self getServiceUrl:BASEJFTURLKEY];
    if (!payUrl) {
        [delegate getPayTypeListFailure:errorParma];
        return;
    }
                   NSDictionary *ddic   = @{@"p25_terminal":@"2"};
         NSMutableDictionary *jsonDic   = [[NSMutableDictionary alloc]initWithDictionary:ddic];
    
    NSError *jsonError = nil;
     NSData *json_Data  = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&jsonError];
    NSData *token_data = [json_Data AES256EncryptWithKey:key iv:iv];
  NSString *jsonBase64 = [token_data base64EncodedString];
            jsonBase64 = [JFTDES replaceNormalCharacter:jsonBase64];
  NSString *encodeBase = [JFTDES encodeToPercentEscapeString:jsonBase64];
    NSString *firstURl = [NSString stringWithFormat:@"%@/services/getServerPayList/%@/%@",payUrl,application_Number,encodeBase];
           NSURL * url = [NSURL URLWithString:firstURl];
    JFT_Log(@"/services/getServerPayList/%@/%@",application_Number,encodeBase);
    [[JFTRequest requestManager]getDataWithUrl:url WithParameters:@{} Sucessfil:^(id returnData) {
        JFT_Log(@"list=%@",returnData);
        if ([returnData isKindOfClass:[NSDictionary class]]) {
             NSDictionary *returnDic = returnData;
                 NSString *flag      = [returnDic objectForKey:@"flag"];
                 NSString *message   = [returnDic objectForKey:@"msg"];
            if ([flag isEqualToString:@"1"]) {
                
            NSString *aesCiphertext = [JFTDES replaceSpecialcharacter:[returnDic objectForKey:@"msg"]];
              NSData *decode_Data = [[NSData dataFromBase64String:aesCiphertext] AES256DecryptWithKey:key iv:iv];
                if (!decode_Data) {
                    if ([delegate respondsToSelector:@selector( getPayTypeListFailure:)]) {
                        [delegate getPayTypeListFailure:@"解密失败"];
                    }
                    return ;
                }
                NSError *jsonError = nil;
                NSArray *listArray = nil;
                         listArray = [NSJSONSerialization
                              JSONObjectWithData:decode_Data
                              options:NSJSONReadingMutableContainers
                              error:&jsonError];
                if ([delegate respondsToSelector:@selector( getPayTypeListSuccess:)]) {
                    [delegate getPayTypeListSuccess:listArray];
                }
            }else{
                if ([delegate respondsToSelector:@selector( getPayTypeListFailure:)]) {
                    [delegate getPayTypeListFailure:message];
                }
            }
        }
        
        
    } failure:^(id failerObjc) {
        if ([delegate respondsToSelector:@selector( getPayTypeListFailure:)]) {
            [delegate getPayTypeListFailure:(NSString*)failerObjc];
        }
    } error:^(NSError *err) {
        if ([delegate respondsToSelector:@selector( getPayTypeListFailure:)]) {
            [delegate getPayTypeListFailure:[NSString stringWithFormat:@"%ld",(long)err.code]];
        }
        if ([self getServiceUrl:MIWENKEY]) {
            NSString *serviceCiphertext = [self getServiceUrl:MIWENKEY];
            NSData *decodeData = [[NSData dataFromBase64String:serviceCiphertext] AES256DecryptWithKey:key iv:iv];
                 NSError *expressError;
            NSDictionary *serviceDic = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingAllowFragments error:&expressError];
                   NSArray *apiServices = serviceDic[@"apiServices"];
                         BOOL isbool = [apiServices containsObject: [self getServiceUrl:BASEJFTURLKEY]];
            if (isbool) {
                         NSInteger i = [apiServices indexOfObject:[self getServiceUrl:BASEJFTURLKEY]];
                if (i == apiServices.count - 1) {
                    [[NSUserDefaults standardUserDefaults]removeObjectForKey:MIWENKEY];
                }else{
                    NSString *nextURL = [apiServices objectAtIndex:i+1];
                    [self storageServiceUrl:nextURL WithKey:BASEJFTURLKEY];
                }
            }
        }
        
        return ;
        
    }];
    
}

#pragma mark - payEntrance

+ (void)payByJftPayModel:(JFTPayModel *)payModel delegate:(id<JftSDKPayDelegate>)delegate{
    if (payModel) {
        jftMydelegate  = delegate;
        if (!payModel.controler||![payModel.controler isKindOfClass:[UIViewController class]]) {
            [delegate openAppFailer:@"请传入当前页面"];
            return;
        }
        junFuTongPayType payType =[self getJunFuTongPayTypeWithPayString:payModel.p7_productcode];
        if (payType == JFTNonePayType) {
               [delegate openAppFailer:@"未找到支付类型"];
        }
        if (payType == JFTWeiXinPayType||payType == JFTJDpayPayType||payType == JFTQQpayPayType) {
            if (payType == JFTWeiXinPayType) {
            if (![JfPay isInstallApp:payType]) {
            if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
                    [delegate openAppFailer:@"未安装微信"];
                    return ;
                
            }
                }
            }
            if (payType == JFTQQpayPayType) {
                if (![JfPay isInstallApp:payType]) {
                      if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
                    [delegate openAppFailer:@"未安装QQ"];
                    return ;
                      }
                }
            }
            
            [self WechatPayByJftpayModel:payModel returnDelegate:delegate];
            
        }
        
        if (payType == JFTAlipayPayType) {
            if (![JfPay isInstallApp:payType]) {
                  if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
                [delegate openAppFailer:@"未安装支付宝"];
                  
                return ;
                  }
            }
        [self WechatPayByJftpayModel:payModel returnDelegate:delegate];

        }
    }
    
}

+ (void)storageServiceUrl:(NSString *)newUrl WithKey:(NSString *)key{
    NSUserDefaults *jftDefaults = [NSUserDefaults standardUserDefaults];
    [jftDefaults removeObjectForKey:key];
    [jftDefaults setObject:newUrl forKey:key];
    [jftDefaults synchronize];
}
+ (NSString *)getServiceUrl:(NSString *)key{
    
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
+ (void) WechatPayByJftpayModel:(JFTPayModel*)model returnDelegate:(id<JftSDKPayDelegate>)delegate{
    if (!model.p1_yingyongnum || !model.p2_ordernumber || !model.p3_money || !model.p6_ordertime || !model.p8_sign || !model.key || !model.iv || !model.p7_productcode){
        [delegate openAppFailer:@"参数缺失"];
        JFT_Log(@"参数缺失");
        return;
    }
    NSString *sysFlag =nil;
    if (model.parameterDic) {
          NSArray *keyArray = [model.parameterDic allKeys];
        NSArray *valueArray = [model.parameterDic allValues];
        if (valueArray.count) {
            for (int i = 0; i < valueArray.count; i++) {
                if ([keyArray[i] isEqualToString:@"systemFlag"]) {
                    sysFlag = valueArray[i];
                }
            }
        }
    }
    __weak typeof(self)weakSelf =self;
        if (![self getServiceUrl:PAYURLKEY]){
            [self getConfigureURLwithApplicationNumber:model.p1_yingyongnum aesKey:model.key andAesIv:model.iv serviceType:sysFlag andDelegate:delegate  payListArray:^(NSString *url) {
                [weakSelf getPaymentParmeterAndPay:model returnDelegate:delegate];
            }];
        }else{
            
            NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
            NSString *miWen = [self getServiceUrl:MIWENKEY];
            NSData *de_data = [[NSData dataFromBase64String:miWen] AES256DecryptWithKey:model.key iv:model.iv];
            NSError *mingError;
   NSDictionary *mingwenDic = [NSJSONSerialization JSONObjectWithData:de_data options:NSJSONReadingAllowFragments error:&mingError];
         NSString *nextSync = [mingwenDic objectForKey:@"nextSync"];
            NSTimeInterval nextInterval = [nextSync doubleValue]/1000;
            if (interval > nextInterval) {
                [self getConfigureURLwithApplicationNumber:model.p1_yingyongnum aesKey:model.key andAesIv:model.iv serviceType:sysFlag andDelegate:delegate  payListArray:^(NSString *url) {
                    [weakSelf getPaymentParmeterAndPay:model returnDelegate:delegate];
                }];
            }else{
                  [weakSelf getPaymentParmeterAndPay:model returnDelegate:delegate];
            }
    }


}
#pragma mark - get Payment parameter  and payAction
+  (void)getPaymentParmeterAndPay:(JFTPayModel*)model returnDelegate:(id<JftSDKPayDelegate>)delegate{
    
     NSString *serviceUrl = [self getServiceUrl:PAYURLKEY];
//   NSString *payurl = @"http://3.order.paycheng.com/jh-web-order/order/receiveOrder";
    if (!serviceUrl) {
        JFT_Log(@"未获取到支付host");
        return ;
    }
    NSDictionary *dic = @{@"p1_yingyongnum":model.p1_yingyongnum,@"p2_ordernumber":model.p2_ordernumber,@"p3_money":model.p3_money,@"p6_ordertime":model.p6_ordertime,@"p7_productcode":model.p7_productcode,@"p8_sign":model.p8_sign,@"p9_signtype":@"1",@"p25_terminal":@"2",@"packageName":[[NSBundle mainBundle] bundleIdentifier],@"p22_sdkversion":EXT_SDKVERSON};
    NSMutableDictionary *jsonDic =[[NSMutableDictionary alloc]initWithDictionary:dic];
    key_String = model.key;
    iv_String  = model.iv;
    model_VC   = model.controler;
    if (model.parameterDic) {
            NSArray *keyArray = [model.parameterDic allKeys];
          NSArray *valueArray = [model.parameterDic allValues];
        if (valueArray.count) {
            for (int i = 0; i < valueArray.count; i++) {
                if (![valueArray[i] isEqualToString:@""]&&![keyArray[i] isEqualToString:@"systemFlag"]) {
                    [jsonDic setObject:[NSString stringWithFormat:@"%@",valueArray[i]] forKey:[NSString stringWithFormat:@"%@",keyArray[i]]];
                }
            }
        }
    }
    [[JFTRequest requestManager] postDataWithUrl:[NSURL URLWithString:serviceUrl] WithParameters:jsonDic Sucessfil:^(id returnData) {

        if ([returnData isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = returnData;
                NSString *flag = [dict valueForKeyPath:@"state"];
            if ([flag integerValue] == 1){
                JFT_Log(@"获取支付参数成功");

                NSDictionary * msg = nil;
                NSData*data = [[dict valueForKeyPath:@"msg"] dataUsingEncoding:NSUTF8StringEncoding];
                 NSError *jsonError = nil;
                NSObject *paraArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
                
                if ([paraArray isKindOfClass:[NSDictionary class]]) {
                    msg = (NSDictionary *)paraArray;
                }else{
                    if ([delegate respondsToSelector:@selector(openAppFailer:)]) {
                        [delegate openAppFailer:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]];
                    }
                    return;
                }
              NSDictionary *infoDic     = [msg valueForKeyPath:@"info"];
                  NSString *mineOrderId = [infoDic valueForKeyPath:@"orderId"];
                  NSNumber *payAction   = [infoDic valueForKeyPath:@"action"];
                  NSString *payUrl      = [infoDic valueForKeyPath:@"url"];
                JFT_Log(@"orderId=%@ payAction=%@",mineOrderId,payAction);

                NSArray *keyArray =[infoDic allKeys];
                NSString * NYBank = @"";
                if (![payUrl isEqualToString:@""]) {
                 
                    if ([keyArray containsObject:@"action"]) {
                    
                    
                    if ([payAction longValue] == 1) {
                        JFTWebViewControler *webvc = [[JFTWebViewControler alloc]init];
                        webvc.initial_VC         = model.controler;
                        webvc.webUrl       = payUrl;
                        webvc.weichatAppid = model.weichatAppid;
               UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:webvc];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [model.controler presentViewController:nav animated:YES completion:^{
                                [delegate openAppSuccessed];
                            }];
                        });
                        
                        webvc.beginOpen = ^(BOOL status) {
                            
                            
                        };
                      webvc.openComplete = ^(BOOL status, NSString *urlStr) {

                [self getResultWithOrderId:[infoDic valueForKeyPath:@"orderId"] andReturnDelegate:delegate];
                        };
                    }
                    if ([payAction longValue] == 0) {
                            order_Id = mineOrderId;
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [[JHShare shareInstance]requestWithWebView:nil andUrl:payUrl];
                            });
                            
                            [JHShare shareInstance].openComplete = ^(BOOL status) {
                                if (status) {
                                    if ([delegate respondsToSelector:@selector(openAppSuccessed)]) {
                                        [delegate openAppSuccessed];
                                    }
                                }else{
                                    [delegate openAppFailer:@"打开失败"];
                                }
                            };
                            
                        
                        }if ([payAction longValue] == 2){
                            if ([self getJunFuTongPayTypeWithPayString:model.p7_productcode]==JFTJDpayPayType) {
                                [self openApplicationWithUrlString:payUrl];
                                [delegate openAppSuccessed];
                            }
                            
                        }
                    
                }else if(![NYBank isEqualToString:@""]){
                    [self sendWeichatOrignSDKPayJson:NYBank];
                    [delegate openAppSuccessed];
                }
                
            }else{
                NSString * message = [dict objectForKey:@"state"];
                [delegate openAppFailer:message];
                
                return;
            }
            }else{
                [delegate openAppFailer:[dict objectForKey:@"state"]];
                JFT_Log(@"%@",[dict objectForKey:@"state"]);
            }
        }
    } failure:^(id failerObjc) {
        [delegate openAppFailer:[NSString stringWithFormat:@"%@",failerObjc]];
    } error:^(NSError *err) {
        [delegate openAppFailer:[NSString stringWithFormat:@"%zi",err.code]];
        if ([self getServiceUrl:MIWENKEY]) {
        NSString *miWen      = [self getServiceUrl:MIWENKEY];
          NSData *de_data    = [[NSData dataFromBase64String:miWen] AES256DecryptWithKey:model.key iv:model.iv];
         NSError *mingError;
    NSDictionary *mingwenDic = [NSJSONSerialization JSONObjectWithData:de_data options:NSJSONReadingAllowFragments error:&mingError];
         NSArray *orderServices = mingwenDic[@"orderServices"];
                    BOOL isbool = [orderServices containsObject: [self getServiceUrl:PAYURLKEY]];
            if (isbool) {
                NSInteger i = [orderServices indexOfObject:[self getServiceUrl:PAYURLKEY]];
                if (i == orderServices.count - 1) {
                    [[NSUserDefaults standardUserDefaults]removeObjectForKey:MIWENKEY];
                      [[NSUserDefaults standardUserDefaults]removeObjectForKey:PAYURLKEY];
                }else{
                    NSString *nextURL = [orderServices objectAtIndex:i+1];
                    [self storageServiceUrl:nextURL WithKey:PAYURLKEY];
                }
            }
        }
        
        return ;

    }];
    
}
# pragma mark - Return result of middle page

+ (void)getResultWithOrderId:(NSString *)orderId andReturnDelegate:(id<JftSDKPayDelegate>)delegate{
    if (orderId) {
            NSData *data     = [[orderId dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:AESKEY iv:AESIV];
        NSString *jsonBase64 = [data base64EncodedString];
                  jsonBase64 = [JFTDES replaceNormalCharacter:jsonBase64];
        NSString *encodeBase = [JFTDES encodeToPercentEscapeString:jsonBase64];
           NSString *baseurl = [self getServiceUrl:BASEJFTURLKEY];
        NSString *urlString  = [NSString stringWithFormat:@"%@/services/getOrderBase/getSdkOrderZFState/%@",baseurl,encodeBase];
                  NSURL *url = [NSURL URLWithString:urlString];
        NSURLSession *sesson = [NSURLSession sharedSession];
  NSURLSessionDataTask *task = [sesson dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                [self payResultType:errorPaidType];
                return ;
            }
            if (data.length) {
                NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
              NSString *miWen = [JFTDES replaceSpecialcharacter:str];
              NSData *de_data = [[NSData dataFromBase64String:miWen] AES256DecryptWithKey:AESKEY iv:AESIV];
                if (!de_data) {
                    [self payResultType:errorPaidType];
                    return;
                }
                NSError *jsonError = nil;
                NSDictionary *ddic = nil;
                if ([[NSJSONSerialization
                      JSONObjectWithData:de_data
                      options:NSJSONReadingMutableContainers
                      error:&jsonError] isKindOfClass:[NSDictionary class]]) {
                    ddic = [NSJSONSerialization
                            JSONObjectWithData:de_data
                            options:NSJSONReadingMutableContainers
                            error:&jsonError];
          NSString *flag = [ddic objectForKey:@"flag"];
                    //                        NSString *msg  =[ddic objectForKey:@"msg"];
                    if ([flag integerValue] == 0||[flag integerValue] == 2) {
             JFTCheckViewController *jftCHvc = [JFTCheckViewController new];
                        jftCHvc.cheack_OrderId = orderId;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [model_VC presentViewController:jftCHvc animated:NO completion:nil];
                        });
                        jftCHvc.openComplete = ^(NSString *result) {
                            if ([result integerValue] == 0) {
                                [self payResultType:UnpaidType];
                            }
                            if ([result integerValue] == 1) {
                                [self payResultType:AlreadyPaidType];
                                
                            }
                            if ([result integerValue] == 2) {
                                [self payResultType:errorPaidType];
                                
                            }
                        };
                    }
                    if ([flag integerValue] == 1) {
                        [self payResultType:AlreadyPaidType];
                    }
                    
                }
                
            }
            
        }];
        [task resume];
    }
    
    
    
}
+ (void)sendWeichatOrignSDKPayJson:(NSString *)json{
    NSData *nyData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError * nyerror = nil;
    NSDictionary *nyDic = [NSJSONSerialization JSONObjectWithData:nyData options:NSJSONReadingMutableContainers error:&nyerror];
    BOOL isJson = [WXApi registerApp:@"wx1d6775c7e499caa9"];
    if (isJson) {
        PayReq *payReq   = [PayReq new];
        payReq.partnerId = nyDic[@"partnerid"];
        payReq.prepayId  = nyDic[@"prepayid"];
        payReq.nonceStr  = nyDic[@"noncestr"];
        payReq.package   = nyDic[@"package"];
        payReq.sign      = [NSString stringWithFormat:@"%@",nyDic[@"sign"]];
        payReq.timeStamp = [nyDic[@"timestamp"] intValue];
        [WXApi sendReq:payReq];
    }
}
#pragma mark -
+ (BOOL)isInstallApp:(junFuTongPayType)type{
    
    if (type == JFTJDpayPayType) {
        return YES;
    }
    if (type == JFTWeiXinPayType) {
      return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]];
    }
    if (type == JFTAlipayPayType) {
        return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay:"]];
    }
    if (type == JFTQQpayPayType) {
        return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]];
    }
    return NO;
}
#pragma mark - Gets the entry of the return result
+ (void)applicationWillEnterForeground{
   
    if (order_Id) {
      NSData *data       = [[order_Id dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:AESKEY iv:AESIV];
    NSString *jsonBase64 = [data base64EncodedString];
              jsonBase64 = [JFTDES replaceNormalCharacter:jsonBase64];
    NSString *encodeBase = [JFTDES encodeToPercentEscapeString:jsonBase64];
    NSString *baseurl    = [self getServiceUrl:BASEJFTURLKEY];
        if (!baseurl) {
            baseurl =@"";
        }
    NSString *urlString  = [NSString stringWithFormat:@"%@/services/getOrderBase/getSdkOrderZFState/%@",baseurl,encodeBase];
       NSURL *url        = [NSURL URLWithString:urlString];
NSURLSession *sesson     = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [sesson dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                if (error) {
                    [self payResultType:errorPaidType];
                    return ;
                }
                if (data.length) {
                NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                    NSString *miWen    = [JFTDES replaceSpecialcharacter:str];
                      NSData *de_data = [[NSData dataFromBase64String:miWen] AES256DecryptWithKey:AESKEY iv:AESIV];
                    if (!de_data) {
                        [self payResultType:errorPaidType];
                        return;
                    }
                     NSError *jsonError = nil;
                NSDictionary *ddic      = nil;
                    if ([[NSJSONSerialization
                         JSONObjectWithData:de_data
                         options:NSJSONReadingMutableContainers
                         error:&jsonError] isKindOfClass:[NSDictionary class]]) {
                        ddic = [NSJSONSerialization
                                JSONObjectWithData:de_data
                                options:NSJSONReadingMutableContainers
                                error:&jsonError];
                        NSString *flag =[ddic objectForKey:@"flag"];
//                        NSString *msg  =[ddic objectForKey:@"msg"];
                        if ([flag integerValue] == 0 || [flag integerValue]==2) {
                            JFTCheckViewController *jftCHvc = [JFTCheckViewController new];
                            jftCHvc.cheack_OrderId = order_Id;
                            dispatch_async(dispatch_get_main_queue(), ^{
                                     [model_VC presentViewController:jftCHvc animated:NO completion:nil];
                            });
                            order_Id = nil;
                            jftCHvc.openComplete = ^(NSString *result) {
                                if ([result integerValue] == 0) {
                                    [self payResultType:UnpaidType];
                                }
                                if ([result integerValue] == 1) {
                                    [self payResultType:AlreadyPaidType];

                                }
                                if ([result integerValue] == 2) {
                                    [self payResultType:errorPaidType];

                                }
                            };
                        }
                        if ([flag integerValue] == 1) {
                            [self payResultType:AlreadyPaidType];
                        }
                     
                    }
               
                }
               
            }];
        [task resume];
    }
    
    
    
}

+ (void)payResultType:(jftResultType)result{
    switch (result) {
        case AlreadyPaidType:
            [jftMydelegate jftPayResult:@"1"];
            break;
        case UnpaidType:
            [jftMydelegate jftPayResult:@"0"];
            break;
        case errorPaidType:
            [jftMydelegate jftPayResult:@"2"];
            break;
        default:
            break;
    }
    
}
+ (junFuTongPayType)getJunFuTongPayTypeWithPayString:(NSString*)payString{
    if (payString.length) {
        if ([payString hasPrefix:@"WX"]) {
            return JFTWeiXinPayType;
        }
        if ([payString hasPrefix:@"ZFB"]) {
            return JFTAlipayPayType;
        }
        if ([payString hasPrefix:@"JD"]) {
            return JFTJDpayPayType;
        }
        if ([payString hasPrefix:@"QQ"]){
            
            return JFTQQpayPayType;
            
        }else{
            return JFTNonePayType;
        }
    }else
    return JFTNonePayType;
    
}
+ (void)openApplicationWithUrlString:(NSString *)UrlString{
    
    if (JFTIOS_VERSION_10) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UrlString] options:@{} completionHandler:^(BOOL success) {
            if (success) {
                JFT_Log(@"打开成功");
            }else
                JFT_Log(@"打开失败");
            
        }];
    } else {
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UrlString]];
    }

}

void CustomLog(const char *func, int lineNumber, NSString *format, ...)
{
    if ([JfPay logEnable]) {
        // 开启了Log
        va_list args;
        va_start(args, format);
           NSString *string = [[NSString alloc] initWithFormat:format arguments:args];
        va_end(args);
        
        NSString *strFormat = [NSString stringWithFormat:@"%s, Line:%i, SDK_Log:%@",func,lineNumber,string];
        NSLog(@"%@", strFormat);
    }
}

+ (BOOL)logEnable {
    return KDS_Log_Switch;
}
+ (void)setLogEnable:(BOOL)flag {
    KDS_Log_Switch = flag;
}
@end
